package com.learning.thread;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author wangyunyun
 */
@Configuration
public class ThreadPoolConfig {

	@Value("${thread.pool.core.size}")
	private Integer corePoolSize;

	@Value("${thread.pool.max.size}")
	private Integer maxPoolSize;

	@Value("${thread.pool.queue.capacity}")
	private Integer queueCapacity;

	@Value("${thread.pool.keep.alive.seconds}")
	private Integer keepAliveSeconds;

	@Value("${thread.pool.thread.name.prefix:common-pool-}")
	private String threadNamePrefix;

	@Bean(name = "commonThreadPool")
	public ThreadPoolTaskExecutor commonPoolTaskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(corePoolSize);
		executor.setMaxPoolSize(maxPoolSize);
		executor.setQueueCapacity(queueCapacity);
		executor.setKeepAliveSeconds(keepAliveSeconds);
		executor.setThreadNamePrefix(threadNamePrefix);
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		executor.setWaitForTasksToCompleteOnShutdown(true);
		executor.initialize();
		return executor;
	}
}
